#include <queue>
#include <vector>
using namespace std;
const int maxn = 5 + 1e5;
using Node = pair<int, int>;

int n, m;
vector<Node> adj[maxn];  // <v, w>

int cnt_in[maxn];  // cnt[i] 是 i 的入度
vector<int> ans;
bool TopSort() {
    // 遍历出边表，求各节点的入度
    for (int u = 1; u <= n; ++u) {
        for (auto &p : adj[u]) {
            int v = p.first;
            ++cnt_in[v];
        }
    }

    queue<int> qe;  // buffer
    for (int u = 1; u <= n; ++u)
        if (cnt_in[u] == 0) qe.push(u);

    while (!qe.empty()) {
        int u = qe.front();
        qe.pop();
        ans.push_back(u);
        for (auto &p : adj[u]) {
            int v = p.first;
            if (--cnt_in[v] == 0) qe.push(v);
        }
    }
    return ans.size() == n;
}
